﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using EnvDTE;
using AssemblyInfoEditor.VersionManagement;
using AssemblyInfoEditor.Project;

namespace AssemblyInfoEditor
{
    /// <summary>
    /// Interaction logic for MyControl.xaml
    /// </summary>
    public partial class SettingsEditor : UserControl
    {
        private DTE ideObject;
        private ProjectAssemblyInfo currentProject;

        public SettingsEditor()
        {
            InitializeComponent();

            ideObject = (DTE)AssemblyInfoEditor.AssemblyInfoEditorPackage.GetGlobalService(typeof(DTE));
            ideObject.Events.BuildEvents.OnBuildBegin += new _dispBuildEvents_OnBuildBeginEventHandler(BuildEvents_OnBuildBegin);
            ideObject.Events.WindowEvents.WindowClosing += new _dispWindowEvents_WindowClosingEventHandler(WindowEvents_WindowClosing);

            projectSelector.SelectionChanged += new SelectionChangedEventHandler(projectCombo_SelectionChanged);

            // Bind our enums to our comboboxes
            buildFormatCombo.ItemsSource = Enum.GetNames(typeof(VersionManagement.IncrementStyle));
            revFormatCombo.ItemsSource = Enum.GetNames(typeof(VersionManagement.IncrementStyle));

            PopulateProjectSelectorBox();
        }

        void WindowEvents_WindowClosing(EnvDTE.Window Window)
        {
            
        }

        void BuildEvents_OnBuildBegin(vsBuildScope Scope, vsBuildAction Action)
        {
            SaveOpenProjectSettings();
        }

        private void PopulateProjectSelectorBox()
        {
            projectSelector.Items.Clear();

            if (AssemblyInfoEditorPackage.ProjectManager.AssemblyInfoCollection.Count == 0)
            {
                AssemblyInfoEditorPackage.ProjectManager.LoadProjectInfo();
            }

            foreach (ProjectAssemblyInfo pai in AssemblyInfoEditorPackage.ProjectManager.AssemblyInfoCollection)
            {
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = pai.Project.Name;
                cbi.Tag = pai;

                projectSelector.Items.Add(cbi);
            }

            if (projectSelector.Items.Count > 0)
            {
                projectSelector.SelectedIndex = 0;
            }
        }

        void projectCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (currentProject != null)
            {
                // Save the project settings before we change the current project
                SaveOpenProjectSettings();
            }

            // to do: fix all this shit. continue converting everything over to using ProjectManager
            // try not to break anything.

            ComboBoxItem item = (ComboBoxItem)e.AddedItems[0];
            ProjectAssemblyInfo project = AssemblyInfoEditorPackage.ProjectManager.AssemblyInfoCollection[item.Content.ToString()];

            project.LoadSettings();

            // Set our current project as the one we just selected
            currentProject = project;

            titleText.Text = project.Title;
            productText.Text = project.Product;
            companyText.Text = project.Company;
            copyrightText.Text = project.Copyright;
            trademarkText.Text = project.Trademark;
            manualVersionText.Text = project.Version.ToString();

            enableVersionIncrementCheckbox.IsChecked = project.IsVersionManagementEnabled;

            buildFormatCombo.SelectedIndex = buildFormatCombo.Items.IndexOf(Enum.GetName(typeof(IncrementStyle), project.Version.BuildIncrementStyle));
            revFormatCombo.SelectedIndex = revFormatCombo.Items.IndexOf(Enum.GetName(typeof(IncrementStyle), project.Version.RevisionIncrementStyle));
        }

        private void ChangeVersionIncrementEnabled(bool Enabled)
        {
            if (Enabled)
            {
                manualVersionText.IsEnabled = false;

                majorText.IsEnabled = true;
                minorText.IsEnabled = true;
                buildFormatCombo.IsEnabled = true;
                revFormatCombo.IsEnabled = true;
            }
            else
            {
                manualVersionText.IsEnabled = true;

                majorText.IsEnabled = false;
                minorText.IsEnabled = false;

                buildFormatCombo.SelectedIndex = buildFormatCombo.Items.IndexOf("None");
                revFormatCombo.SelectedIndex = revFormatCombo.Items.IndexOf("None");

                buildFormatCombo.IsEnabled = false;
                revFormatCombo.IsEnabled = false;
            }
        }

        #region Misc. Event Handlers

        private void enableVersionIncrementCheckbox_Unchecked(object sender, RoutedEventArgs e)
        {
            ChangeVersionIncrementEnabled(false);
        }

        private void enableVersionIncrementCheckbox_Checked(object sender, RoutedEventArgs e)
        {
            ChangeVersionIncrementEnabled(true);
        }

        #endregion

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            SaveOpenProjectSettings();
        }

        private void SaveOpenProjectSettings()
        {
            ProjectAssemblyInfo pas = currentProject;

            pas.Title = titleText.Text;
            pas.Product = productText.Text;
            pas.Company = companyText.Text;
            pas.Copyright = copyrightText.Text;
            pas.Trademark = trademarkText.Text;
            pas.IsVersionManagementEnabled = (bool)enableVersionIncrementCheckbox.IsChecked;

            if (!pas.IsVersionManagementEnabled)
            {
                pas.Version = ManagedVersion.ConvertFromString(manualVersionText.Text);
                
                pas.Version.BuildIncrementStyle = IncrementStyle.None;
                pas.Version.RevisionIncrementStyle = IncrementStyle.None;
            }
            else
            {
                if ((buildFormatCombo.SelectedItem != null) && (revFormatCombo.SelectedItem != null))
                {
                    IncrementStyle bStyle = (IncrementStyle)Enum.Parse(typeof(IncrementStyle), buildFormatCombo.SelectedItem.ToString());
                    IncrementStyle rStyle = (IncrementStyle)Enum.Parse(typeof(IncrementStyle), revFormatCombo.SelectedItem.ToString());

                    pas.Version.MajorVersion = Int32.Parse(majorText.Text);
                    pas.Version.MinorVersion = Int32.Parse(minorText.Text);
                    pas.Version.BuildIncrementStyle = bStyle;
                    pas.Version.RevisionIncrementStyle = rStyle;
                }
            }

            AssemblyInfoEditorPackage.ProjectManager.AssemblyInfoCollection[pas.Project.Name] = pas;
        }

        private void UpdateVersionPreviewLabel()
        {
            if ((buildFormatCombo.SelectedItem != null) && (revFormatCombo.SelectedItem != null))
            {
                IncrementStyle bStyle = (IncrementStyle)Enum.Parse(typeof(IncrementStyle), buildFormatCombo.SelectedItem.ToString());
                IncrementStyle rStyle = (IncrementStyle)Enum.Parse(typeof(IncrementStyle), revFormatCombo.SelectedItem.ToString());

                ManagedVersion vPreview = new ManagedVersion();
                vPreview.MajorVersion = Int32.Parse(majorText.Text);
                vPreview.MinorVersion = Int32.Parse(minorText.Text);
                vPreview.BuildIncrementStyle = bStyle;
                vPreview.RevisionIncrementStyle = rStyle;
                vPreview.Increment(DateTime.Now);

                versionPreview.Text = vPreview.ToString();
            }
        }

        private void buildFormatCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateVersionPreviewLabel();
        }

        private void revFormatCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateVersionPreviewLabel();
        }

        private void AssemblyInfoHelperWindow_Unloaded(object sender, RoutedEventArgs e)
        {
            //SaveOpenProjectSettings();
        }

        // auto-generated with project creation. keep just in case we need for reference or something
        /*[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")]
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(string.Format(System.Globalization.CultureInfo.CurrentUICulture, "We are inside {0}.button1_Click()", this.ToString()),
                            "AutoVersion Settings");

        }*/
    }
}